package models;

import java.util.Calendar;
import java.util.Date;
import java.util.List;
import com.google.appengine.api.datastore.Link;
import play.data.binding.As;
import play.data.validation.Valid;
import siena.DateTime;
import siena.Generator;
import siena.Id;
import siena.Model;
import siena.Query;
import siena.core.One;
import siena.core.Referenced;
import siena.core.lifecycle.PreInsert;
import siena.core.lifecycle.PreUpdate;
import siena.core.lifecycle.PostDelete;
import siena.embed.At;
import siena.embed.Embedded;
import siena.embed.EmbeddedList;
import siena.embed.Embedded.Mode;
import utils.files.GAEFileService;

public class Photo extends Content {
	
	public String filename;
	public User owner;
	//Thumbnail
	public Link picture;
	@Valid
	@Embedded(mode=Mode.NATIVE)
	public Image original;
	@Valid
	@Embedded
	public List<Image> images;
	
	@EmbeddedList
	public class Image {
		@At(0) public Integer height;
		@At(1) public Integer width;
		@At(2) public String source;
		@At(3) public String key;
	}
	
	public static Query<Photo> all() {
        return all(Photo.class);
	}
	
	public static Query<Photo> all(User owner) {
        return all().filter("owner", owner);
	}
	
	public static int countByOwner(User owner) {
		return all().filter("owner", owner).count();
	}
	
	
	public static Photo findById(Long id) {
		Photo photo = all().filter("id", id).get();
		return photo;
	}
	
	public static List<Photo> paginate(Query<Photo> query, int offset, int limit) {
		return query.fetch(limit, offset);
	}
	
	
	@PostDelete
	protected void removeFiles() {
		GAEFileService.deleteFile(this.original.key);
	}
}